'use client';
import { useEffect, useRef, useState } from 'react';
import './DeliveryList.scss';
import { formatCurrency } from '@/utils/common';

const DeliveryList = ({ zoneRates }: { zoneRates: Obj }) => {
  const [deliveryList, setDeliveryList] = useState<any[]>([]);

  const initComponent = (zone_rates: Obj) => {
    const deliveries: Obj[] = [];
    const excludeKeys = ['created_at', 'group_id', 'sku'];
    Object.keys(zone_rates).forEach((key: string) => {
      if (excludeKeys.includes(key)) return;
      const val = zone_rates[key];
      deliveries.push({
        name: key.toUpperCase(),
        val: val,
        desc:
          val >= 9999
            ? 'Undeliverable'
            : val == 0
              ? 'Free Shipping'
              : formatCurrency(val),
        class:
          val >= 9999
            ? 'delivery-undeliverable'
            : val == 0
              ? 'delivery-freeshipping'
              : '',
      });
    });
    deliveries.sort((a, b) => a.name != 'nz' || a.name.localeCompare(b.name));
    setDeliveryList(deliveries);
  };
  const initComponentRef = useRef(initComponent);
  initComponentRef.current = initComponent;

  useEffect(() => {
    zoneRates && initComponentRef.current(zoneRates);
  }, [zoneRates]);

  return (
    <div className="content-infos-delivery">
      <div className="content-infos-delivery-title">
        <span className="iconfont icon-delivery"></span>Delivery
      </div>
      <div className="content-infos-delivery-list">
        {deliveryList.map((delivery: Obj, index: number) => (
          <div key={index} className="content-infos-delivery-item">
            <span className="content-infos-delivery-item-key">
              {delivery.name}
            </span>
            <span
              className={'content-infos-delivery-item-val ' + delivery.class}
            >
              {delivery.desc}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default DeliveryList;
